package edu.neu.cs6515.xml.w12;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import org.apache.commons.io.IOUtils;

import edu.neu.cs6515.net.IProxyInOutput;
import edu.neu.cs6515.net.InputOutputException;

import lombok.Getter;

public class XMLBroker implements IProxyInOutput {

    
    
    Marshaller marshaller;

    Unmarshaller unmarshaller;

    @Getter
    Writer out;

    @Getter
    Reader in;

    public XMLBroker(final Marshaller marshaller,
            final Unmarshaller unmarshaller, final Writer out, final Reader in) {
        super();
        this.marshaller = marshaller;
        this.unmarshaller = unmarshaller;
        this.out = out;
        this.in = in;
    }

    /* (non-Javadoc)
     * @see edu.neu.cs6515.xml.w12.IProxyPlayerInOutput#respond(java.lang.Object)
     */
    @Override
    public void respond(final Object obj) throws InputOutputException {
            try {
                marshaller.marshal(obj, out);
                out.flush();
            } catch (JAXBException e) {
                e.printStackTrace();
                throw new InputOutputException("marshal failed");
            } catch (IOException e) {
                e.printStackTrace();
                throw new InputOutputException("flush failed");
            }
            
    }

    /* (non-Javadoc)
     * @see edu.neu.cs6515.xml.w12.IProxyPlayerInOutput#receive()
     */
    @Override
    public Object receive() throws InputOutputException {
            try {
                return unmarshaller.unmarshal(in);
            } catch (JAXBException e) {
                e.printStackTrace();
                throw new InputOutputException("unmarshall failed");
            }
    }
}
